// routes/api/cart.js
const express = require("express");
const router = express.Router();
const passport = require("passport");
const Cart = require("../../../models/Cart");
const Shop = require("../../../models/Shop");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// 辅助函数：计算购物车中所有商品的总金额
function calculateTotalAmount(cart) {
  return cart.items
    .reduce((total, item) => total + parseFloat(item.price) * item.quantity, 0)
    .toFixed(2);
}

// @route POST api/cart/add
router.post("/add", auth, async (req, res) => {
  try {
    const { productId, typeId, quantity, defaultAddress } = req.body;
    const user = req.user.id;

    const shop = await Shop.findOne({ "products._id": productId });
    if (!shop) {
      return res.status(404).json({ success: false, error: "未找到商品" });
    }

    const product = shop.products.id(productId);
    if (!product) {
      return res.status(404).json({ success: false, error: "未找到商品" });
    }

    const productType = product.types.id(typeId);
    if (!productType) {
      return res.status(404).json({ success: false, error: "未找到商品类型" });
    }

    let cart = await Cart.findOne({ user });
    const cartItem = {
      productId: product._id,
      typeId: productType._id,
      name: product.name,
      photo: productType.photo,
      type: productType.kind,
      price: productType.price,
      quantity,
      defaultAddress,
      isSelected: false,
    };

    if (cart) {
      const itemIndex = cart.items.findIndex(
        (item) =>
          item.productId.toString() === productId &&
          item.typeId.toString() === typeId
      );
      if (itemIndex > -1) {
        cart.items[itemIndex].quantity += quantity;
      } else {
        cart.items.push(cartItem);
      }
      cart.totalAmount = calculateTotalAmount(cart);
      cart.updatedAt = Date.now();
      await cart.save();
    } else {
      cart = new Cart({
        user,
        items: [cartItem],
        totalAmount: (parseFloat(cartItem.price) * quantity).toFixed(2),
      });
      await cart.save();
    }

    // 返回简化后的响应结构
    res
      .status(200)
      .json({ success: true, data: { cart, totalCount: cart.items.length } });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route GET api/cart
router.get("/", auth, async (req, res) => {
  try {
    const cart = await Cart.findOne({ user: req.user.id });
    if (!cart) {
      return res.status(404).json({ success: false, error: "购物车为空" });
    }
    // 返回简化后的响应结构
    res
      .status(200)
      .json({ success: true, data: { cart, totalCount: cart.items.length } });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route PUT api/cart/update
router.put("/update", auth, async (req, res) => {
  try {
    const updates = req.body.updates; // 期待一个更新数组
    const cart = await Cart.findOne({ user: req.user.id });

    if (!cart) {
      return res.status(404).json({ success: false, error: "购物车为空" });
    }

    for (const update of updates) {
      const { cartItemId, quantity, isSelected, defaultAddress } = update;
      const item = cart.items.id(cartItemId);
      if (item) {
        if (quantity !== undefined) item.quantity = quantity;
        if (isSelected !== undefined) item.isSelected = isSelected;
        if (defaultAddress !== undefined) item.defaultAddress = defaultAddress;
      } else {
        return res
          .status(404)
          .json({ success: false, error: `未找到商品: ${cartItemId}` });
      }
    }

    cart.totalAmount = calculateTotalAmount(cart);
    cart.updatedAt = Date.now();
    await cart.save();
    // 返回简化后的响应结构
    res
      .status(200)
      .json({ success: true, data: { cart, totalCount: cart.items.length } });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route DELETE api/cart/remove
router.delete("/remove", auth, async (req, res) => {
  try {
    const { cartItemId } = req.body;
    const cart = await Cart.findOne({ user: req.user.id });

    if (!cart) {
      return res.status(404).json({ success: false, error: "购物车为空" });
    }

    const itemIndex = cart.items.findIndex(
      (item) => item._id.toString() === cartItemId
    );
    if (itemIndex > -1) {
      cart.items.splice(itemIndex, 1);
      cart.totalAmount = calculateTotalAmount(cart);
      cart.updatedAt = Date.now();
      await cart.save();
      // 返回简化后的响应结构
      res
        .status(200)
        .json({ success: true, data: { cart, totalCount: cart.items.length } });
    } else {
      return res.status(404).json({ success: false, error: "未找到商品" });
    }
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
